﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using System.ComponentModel;


namespace Common
{
    public static class EnumHelper
    {
        public static string GetDescription(this Enum en)
        {
            string strValue = en.ToString();
            FieldInfo fieldinfo = en.GetType().GetField(strValue);
            Object[] objs = fieldinfo.GetCustomAttributes(typeof(DescriptionAttribute), false);
            if (objs == null || objs.Length == 0)
            {
                return strValue;
            }
            else
            {
                DescriptionAttribute da = (DescriptionAttribute)objs[0];
                return da.Description;
            }
        }

        public static bool IsIgnore(this Enum en)
        {
            string strValue = en.ToString();
            FieldInfo fieldinfo = en.GetType().GetField(strValue);
            Object[] objs = fieldinfo.GetCustomAttributes(typeof(EnumIgnoreAttribute), false);
            return objs != null && objs.Length > 0;         
        }

        public static Dictionary<int, string> ConvertEnumToDictionary(Type type)
        {
            Dictionary<int, string> enumDictionary = new Dictionary<int, string>();
            if (type.IsEnum)
            {
                foreach (Enum en in Enum.GetValues(type))
                {
                    if (!en.IsIgnore())
                    {
                        enumDictionary.Add(Convert.ToInt32(en), en.GetDescription());
                    }
                }
            }
            return enumDictionary;
        }

        public static List<KeyValuePair<int, string>> ConvertEnumToKeyValueList(Type type)
        {
            List<KeyValuePair<int, string>> keyValueList = new List<KeyValuePair<int, string>>();
            if (type.IsEnum)
            {
                foreach (Enum en in Enum.GetValues(type))
                {
                    if (!en.IsIgnore())
                    {
                        keyValueList.Add(new KeyValuePair<int, string>(Convert.ToInt32(en), en.GetDescription()));
                    }
                }
            }
            return keyValueList;
        }

        public static List<string> GetEnumDescriptionList(Type type)
        {
            List<string> desctiptionList = new List<string>();
            if (type.IsEnum)
            {
                foreach (Enum en in Enum.GetValues(type))
                {
                    if (!en.IsIgnore())
                    {
                        desctiptionList.Add(en.GetDescription());
                    }
                }
            }
            return desctiptionList;
        }
    }
    public class EnumIgnoreAttribute : Attribute
    {
    }
}
